<template>
  <div style="width:90%;">
    <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px">
      <el-button @click="goback()" size="mini" type="primary" style="margin-left:1000px">返回</el-button>

      <el-form-item label="活动描述：" prop="activityDesc">
        <el-input type="textarea" v-model="planForm.activityDesc" :disabled="disabledFlag" placeholder="请输入活动描述"
          maxlength="120" show-word-limit :autosize="{ minRows: 2 }" style="width:650px;"></el-input>
      </el-form-item>

      <el-form-item label="开始时间：" prop="beginTime">
        <el-date-picker v-model="planForm.beginTime" type="date" placeholder="请选择开始时间" value-format="yyyy-MM-dd"
          :disabled="disabledFlag" style="width:325px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间：" prop="endTime">
        <el-date-picker v-model="planForm.endTime" type="date" placeholder="请选择结束时间" value-format="yyyy-MM-dd"
          :disabled="disabledFlag" style="width:325px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-radio-group v-model="planForm.status" :disabled="disabledFlag">
          <el-radio-button label="1">不发布</el-radio-button>
          <el-radio-button label="2">发布</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品范围：">
        <el-radio-group v-model="planForm.goodsAll" :disabled="disabledFlag"
          @change="handleCheckAllChange(planForm.goodsAll)">
          <el-radio-button label="1">全部</el-radio-button>
          <el-radio-button label="0">指定</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-input v-model="filtersForm.value" @change="changeValue(filtersForm.value)" style="width:325px;" clearable
          placeholder="请输入关键字筛选" v-show="planForm.goodsAll == '0' && !disabledFlag"></el-input>
        <el-button type="primary" size="mini" icon="el-icon-search" v-show="planForm.goodsAll == '0' && !disabledFlag"
          @click="filterHandler2(filtersForm.value, planCouponList)">筛选</el-button>
        <el-button @click="resetDateFilter, filterHandler2('', planCouponList)" type="primary" size="mini"
          v-show="planForm.goodsAll == '0' && !disabledFlag">重置</el-button>
      </el-form-item>

      <el-form-item label="参与商品：" prop="planCouponList">
        <el-table ref="table" :data="planCouponList" :row-style="rowClass" @selection-change="planCouponChecked"
          @filter-change="tableFilter" border style="font-size: 10px;width:100%;" height="300"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <el-table-column :selectable="checkboxT" type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="goodsName" sortable column-key="goodsName" label="商品名称" header-align="center"
            :filters="filtersList" :filter-method="filterHandler"></el-table-column>
          <el-table-column prop="goodsTypeName" sortable label="商品分类" header-align="center"></el-table-column>
          <el-table-column prop="unitName" sortable label="计量单位" header-align="center"></el-table-column>
          <el-table-column prop="salePrice" sortable label="商品价格" header-align="center" align="right"></el-table-column>
          <!-- <el-table-column prop="memberPrice" sortable label="会员价" header-align="center">
                        <template slot-scope="scope">
                            <el-input
                                :maxlength="8"
                                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                                v-model="scope.row.memberPrice"
                                style="width: 120px; text-align-last: right;"
                                v-on:input="compare(scope.row,scope.$index)"
                            ></el-input>
                        </template>
</el-table-column>-->
          <el-table-column prop="memberPrices" width="400" label="会员价" header-align="center">
            <template slot-scope="scope">
              <el-input :readonly="disabledFlag" :maxlength="8"
                oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                v-for="(item, index) in scope.row.memberPrices" :key="index" :value="item"
                v-model="scope.row.memberPrices[index]" placeholder="请输入值" style="width: 90px; text-align-last: right;"
                @blur="compare2($event, scope.row.salePrice, scope.row.memberPrices[index], index, scope.$index)">
                <el-input v-if="index != scope.row.memberPrices.length - 1">{{ item }};</el-input>
                <el-input v-else>{{ item }}</el-input>
              </el-input>
              <el-button type="text" :disabled="scope.row.memberPrices.length < 1 || disabledFlag"
                @click="deleteItem(scope.row.memberPrices, scope.row.memberPrices.length - 1, $event)">删除</el-button>
              <el-button type="text" :disabled="disabledFlag"
                @click="toAdd(scope.row.memberPrices, scope.row.memberPrice)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('planForm')" v-show="!this.disabledFlag">保 存</el-button>
        <el-button @click="resetForm('planForm')" v-show="!this.disabledFlag">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  queryPromotionList,
  queryCouponById,
  savePromotion,
  updatePromotionStatus,
  queryStoreByPlanId,
  queryStoreInfo
} from "@/api/promotionProgramEdit";
import {
  queryChooseGoodsList,
  saveGoodsActivityWithGoods,
  queryGoodsStoreList
} from "@/api/memberPriceEdit";
import { queryGradelevelRule } from "@/api/membergrade";

export default {
  data() {
    return {
      selectRow: [],
      selectData: [],
      logininfo: {},
      filtersList: [],
      filtersForm: {
        text: "",
        value: ""
      },
      checkedarr: [],
      orgList: [],
      couponListshop: [],
      dialogVisibledetail: false,
      loading: true,
      lsPlanCouponList: [],
      lsCouponList: [],
      lsCouponListone: [],
      planCouponList: [],
      planCouponListone: [],
      couponList: [],
      planMemberRangeList: [],
      memberRangeList: [],
      lsPlanMemberLevelList: [],
      lsMemberLevelList: [],
      lsCouponIndex: "",
      lsShopList: [],
      shopList: [],
      couponUseScopeList: [],
      couponShopLevelList: [],
      currentCouponId: "",
      currentCouponLevelIds: "",
      fileList: [],
      planForm: {
        uuid: "",
        activityDesc: "",
        beginTime: "",
        endTime: "",
        memberRange: "",
        status: "",
        goodsAll: "",
        goodsList: []
      },
      formCoupon: {
        couponName: ""
      },
      formShop: {
        shopName: ""
      },
      goodsId: [],
      goodsIdone: [],
      dialogVisibleCoupon: false,
      dialogVisibleShop: false,
      dialogVisibleMemberRange: false,
      disabledFlag: false,
      updateFlag: false,
      dialogVisibleImg: false,
      dialogImageUrl: "",
      listQuery: {
        current: 1,
        size: 10
      },
      total: 0,
      planRules: {
        activityDesc: [
          { required: true, message: "请输入方案名称", trigger: "blur" }
        ],
        beginTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    var v = this.$route.params.edit;
    this.disabledFlag = this.$route.params.falg;
    this.updateFlag = this.$route.params.updateFlag;
    if (v) {
      // 修改，回显值
      this.planForm.uuid = v.uuid;
      this.planForm.activityDesc = v.activityDesc;
      this.planForm.activityDesc = v.activityDesc;
      this.planForm.beginTime = v.beginTime;
      this.planForm.endTime = v.endTime;
      this.planForm.memberRange = v.memberRange;
      this.planForm.status = String(v.status);
      this.planForm.goodsAll = String(v.goodsAll);
      this.planCouponList = v.goodsList;
      if (this.planCouponList.length > 0) {
        this.planCouponList.forEach((item, i) => {
          item.salePrice = item.price;
          item.memberPrices = item.memberPrices.split(',');
        });
      }
      this.planCouponListone = v.goodsList;
      this.goodsId = v.goodsList.map(o => {
        return { goodsId: o.goodsId, memberPrices: o.memberPrices };
      });
      this.queryChooseGoodsListInit();
    } else {
      // 新增，默认值
      this.updateFlag = false;
      this.disabledFlag = false;
      this.planForm.uuid = "";
      this.planForm.memberRange = "1";
      this.planForm.status = "1";
      this.planForm.goodsAll = "0";
      this.queryChooseGoodsListInit();
      this.getMemberlevel();
    }
  },
  watch: {
    selectData(row) {
      this.selectRow = []; if (row.length > 0) {
        row.forEach((item, index) => {
          this.selectRow.push(this.planCouponList.indexOf(item));
        });
      }
    }
  },
  methods: {
    toAdd(v, param) {
      let array = '';
      v.push(array);
    },
    deleteItem(items, index, event) {
      // var $current = $(event.target);
      // $current.prev().attr('key',2);
      items.splice(index, 1);
    },
    checkboxT(row, index) {
      if (this.disabledFlag && row.uuid) {
        return false
      } else {
        return true
      }
    },
    filterHandler3(value) {
      return this.planCouponList.filter(item => {
        var reg = new RegExp(value, "i");
        return !value || reg.test(item.goodsName);
      });
    },
    tableFilter(filters) {
      return this.planCouponList.filter(item => {
        var reg = new RegExp(this.filtersList[0].value, "i");
        return !value || reg.test(item.goodsName);
      });
    },
    seedetail() {
      this.dialogVisibledetail = true;
      let data = {
        size: 5,
        current: 1,
        condition: {
          warzoneName: "",
          uuid: this.planForm.uuid,
          shopName: this.formCoupon.orgName
        },
        ascs: [],
        descs: []
      };
      queryGoodsStoreList(data).then(res => {
        this.couponListshop = res.records;
        console.log(this.couponListshop, "888");
      });
    },
    goback() {
      this.$router.go("-1");
    },
    sortKey(key) {
      return function (a, b) {
        let x = a[key];
        let y = b[key];
        return ((x < y) ? -1 : (x > y) ? 1 : 0);
      }
    },

    queryChooseGoodsListInit() {
      let data = {
        size: 999,
        current: 1,
        condition: {
          goodsTypeId: "",
          barCode: ""
        },
        ascs: [],
        descs: []
      };
      queryChooseGoodsList(data)
        .then(res => {
          this.planCouponList = res.records;
          this.lsShopList = res.records;
          this.planCouponList.forEach((item, i) => {
            this.$set(item, "memberPrice", item.salePrice);
            let list = [];
            if (!this.updateFlag && !this.disabledFlag) { list = [item.salePrice]; }
            this.$set(item, "memberPrices", list);
          });
        })
        .then(() => {
        })
        .then(() => {
          if (true) {
            for (let i = 0; i < this.planCouponList.length; i++) {
              for (let j = 0; j < this.planCouponListone.length; j++) {
                if (this.planCouponList[i].uuid == this.planCouponListone[j].goodsId) {
                  this.$refs.table.toggleRowSelection(this.planCouponList[i], true);
                  this.planCouponList[i].memberPrices = this.planCouponListone[j].memberPrices;
                }
              }
            }
          }
        })
        .then(() => {
          this.planCouponList.sort(this.sortKey('memberPrices')).reverse();
        });
      this.loading = false;
    },
    queryChooseGoodsList() {
      let data = {
        size: 999,
        current: 1,
        condition: {
          goodsTypeId: "",
          barCode: ""
        },
        ascs: [],
        descs: []
      };
      queryChooseGoodsList(data).then(res => {
        this.couponList = res.records;
        this.planCouponList = res.records;
        this.planCouponList.forEach((item, i) => {
          item.memberPrice = item.salePrice;
        });
        console.log(this.couponList, "888");
        console.log(this.planCouponList, "999");
        // 去掉已选的;
        for (var i in this.planCouponList) {
          this.removeByValue(
            this.couponList,
            "uuid",
            this.planCouponList[i].uuid
          );
        }
      });
      this.loading = false;
    },
    getMemberlevel() {
      let data = {
        size: 10,
        current: 1,
        condition: {},
        ascs: [],
        descs: []
      };
      queryGradelevelRule(data).then(res => {
        this.memberRangeList = res.records;
        // 去掉已选的
        for (var i in this.planMemberRangeList) {
          this.removeByValue(
            this.memberRangeList,
            "uuid",
            this.planMemberRangeList[i].uuid
          );
        }
      });
      this.loading = false;
    },

    planCouponChecked(row) {
      this.selectData = row;
      this.lsPlanCouponList = row;
      if (this.lsPlanCouponList.length == this.lsShopList.length) { this.planForm.goodsAll = "1" }
      else { this.planForm.goodsAll = "0" }
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(185, 221, 249, 0.75)" };
      }
    },
    couponChecked(row) {
      this.lsCouponList = row;
    },
    selectCoupon() {
      // 显示选择卡券对话框
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      this.queryChooseGoodsList();
    },
    deleteCoupon() {
      // 删除已选择的卡券
      this.couponList = this.couponList.concat(this.lsPlanCouponList);
      for (var i in this.lsPlanCouponList) {
        this.removeByValue(
          this.planCouponList,
          "uuid",
          this.lsPlanCouponList[i].uuid
        );
      }
      this.planForm.goodsList = this.planCouponList;
    },
    couponConfirm() {
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      this.lsCouponListone = this.lsCouponList;
      this.planCouponList = this.planCouponList.concat(this.lsCouponList);

      for (var i in this.lsCouponList) {
        this.removeByValue(this.couponList, "uuid", this.lsCouponList[i].uuid);
      }

      this.planForm.goodsList = this.planCouponList;

      this.planForm.goodsList = this.planForm.goodsList.map(o => {
        return { goodsId: o.uuid, memberPrice: o.memberPrice };
      });
    },

    submitForm(formName) {
      if (
        this.planForm.activityDesc == "" ||
        this.planForm.activityDesc == null
      ) {
        this.$message.error("请输入活动描述");
        return;
      }
      if (this.planForm.beginTime == "" || this.planForm.beginTime == null) {
        this.$message.error("请输入开始时间");
        return;
      }
      if (this.planForm.endTime == "" || this.planForm.endTime == null) {
        this.$message.error("请输入结束时间");
        return;
      }
      if (this.planForm.beginTime > this.planForm.endTime) {
        this.$message.error("结束时间不能早于开始时间");
        return;
      }
      if (this.lsPlanCouponList == null || this.lsPlanCouponList.length == 0) {
        this.$message.error("请选择参与商品");
        return;
      }
      let isEvery = this.lsPlanCouponList.some((item, i) => {
        console.log(item.memberPrices, "item.memberPrices")
        let listT = item.memberPrices;
        let flag = listT.some((item, i) => {
          return item == "" ||
            item == undefined ||
            item == null ||
            item.length == 0
        });
        return flag;
      });
      if (isEvery) {
        this.$message.error("请输入选中商品的会员价，不允许空值");
        return;
      }

      this.planForm.goodsList = this.lsPlanCouponList.map(o => {
        return { goodsId: o.uuid, memberPrices: o.memberPrices.join(',') };
      });

      if (this.$route.params.edit) {
        // this.goodsId = this.planCouponListone.map(o => {
        //   return { goodsId: o.goodsId, memberPrice: o.memberPrice };
        // });
        // this.goodsIdone = this.lsCouponListone.map(o => {
        //   return { goodsId: o.uuid, memberPrice: o.memberPrice };
        // });
        // this.goodsId = this.goodsId.concat(this.goodsIdone);
      } else {
        // let isEvery = this.planForm.goodsList.some((item, i) => {
        //   return (
        //     item.memberPrice == "" ||
        //     item.memberPrice == undefined ||
        //     item.memberPrice == null
        //   );
        // });
        // if (isEvery) {
        //   this.$message.error("请输入选择商品的会员价");
        //   return;
        // }
      }

      saveGoodsActivityWithGoods(this.planForm).then(res => {
        if (res.code == "1") {
          this.$message({
            showClose: true,
            message: res.message,
            type: "success"
          });
          this.$router.push("memberPrice");
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error"
          });
        }
      });
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getShopList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getShopList();
    },
    // 数组，属性，属性值
    removeByValue: function (arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },

    handleRemove(file, fileList) {
      let newfileList = [];
      fileList.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url
        };
        newfileList.push(data);
      });
      this.fileList = newfileList;
    },
    upLoadPic(file, fileList) {
      var picUrl = file.result;
      var name = fileList.name;
      let data = {
        name: name,
        url: picUrl
      };
      this.fileList.push(data);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push("memberPrice");
    },
    handleCheckAllChange(value) {
      this.$refs.table.toggleAllSelection();
    },
    resetDateFilter() {
      this.$refs.table.clearFilter("goodsName");
      // this.filtersList = [];
    },
    filterHandler(value, row) {
      return row.goodsName.indexOf(value) != -1;
    },
    filterHandler2(value, items) {
      if (value == "") {
        this.filtersForm.value = "";
        this.queryChooseGoodsListInit();
      } else {
        this.planCouponList = this.lsShopList.filter((item, i) => {
          return this.filterHandler(value, item);
        });
      }
      // var searchRegex = new RegExp(value, 'i');
      // var arr=[];
      // for(var i= 0, j = items.length; i < j; i++){
      //         if(searchRegex.test(items[i].goodsName)){
      //             arr[i].push(items[i][item]);
      //     }
      // }
      // return arr;
    },
    changeValue(value) {
      if (value != "") {
        this.filtersList.push({ text: value, value: value });
      }
    },
    handleCheckChange() {
      let res = this.$refs.tree.getCheckedNodes();
      this.resone = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      console.log(this.resone, "iiii");
      this.checkedarr = [];
      this.btnarr = [];
      res.forEach(item => {
        // arr.push(item.id);
        // console.log(item, "ll2tt");
        if (item.resourceLevel == null) {
          this.btnarr.push(item.id);
          console.log(this.btnarr, "ll2ee");
        } else {
          //   this.checkedarr.push(item.id);
          //   this.arrone = arr;
          console.log(this.checkedarr, "ll2");
        }
      });
    },
    compare(value, index) {
      var number = value.salePrice;
      var val = value.memberPrice;
      if (val === null || val === undefined || val === "") {
        this.$message({ showClose: true, message: "请输入会员价", type: "info" });
        this.planCouponList[index].memberPrice = ''
        return false;
      } else {
        if (Number(val) > Number(number)) {
          this.$message({ showClose: true, message: "会员价不能高于商品价", type: "info" });
          this.planCouponList[index].memberPrice = number
          return false;
        }
      }
    },
    compare2(e, value, val, index, $index) {
      let that = this;
      let number = value;
      const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (val === null || val === undefined || val === "") {
        this.$message({ showClose: true, message: "请输入会员价", type: "info" });
        e.target.value = "";
        return false;
      } else {
        if (!reg.test(Number(val))) {
          this.$message({ showClose: true, message: "金额格式错误", type: "error" });
          e.target.value = "";
          return false;
        }
        if (Number(val) > Number(number)) {
          this.$message({ showClose: true, message: "会员价不能高于商品价", type: "info" });
          e.target.value = "";
          return false;
        }
        let isRepeat = this.planCouponList[$index].memberPrices.some((item, i) => {
          if (i != index) { return Number(item) == Number(val); }
        });
        if (isRepeat) {
          this.$message({ showClose: true, message: "同一商品会员价重复设置", type: "info" });
          e.target.value = "";
          return false;
        }
      }
    },

  }
};</script>>
<style lang="less" scoped>
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}

.el-input {
  width: 60%;
}

.search-form-inline {
  border: 1px solid #ebeef5;
  line-height: 30px;
  padding: 12px;
  margin-bottom: 5px;
}
</style>
